package com.wbc.smartHome.Interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wbc.smartHome.model.Result;
import com.wbc.smartHome.util.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class UserTokenInterceptor implements HandlerInterceptor {

/*
    拦截器处理方法
    当请求达到处理器前，进入到拦截器进行处理
    返回true--离开拦截器向后执行到达处理器
    返回flase--不再向后执行
*/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userToken = request.getHeader("userToken");
        if (JWTUtil.verify(userToken)) {
            return true;
        }
        else {
            response.setContentType("text/html;charset=utf-8");
            Result result = new Result(501,"userToken验证失败",null);
            response.getWriter().write(new ObjectMapper().writeValueAsString(result));
        }
        return false;
    }
}
